# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# openUBMC is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#         http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
import os

from conans import AutoToolsBuildEnvironment, ConanFile, tools


class LibyamlConan(ConanFile):
    name = "libyaml"
    license = "Apache License V2.0"
    generators = "cmake"
    description = "LibYAML is a YAML parser and emitter library"
    chost = None
    settings = "os", "compiler", "build_type", "arch"
    exports_sources = ["permissions.ini"]
    options = {
        "shared": [True, False]
    }
    default_options = {"shared": True}

    @property
    def _source_subfolder(self):
        return "source_subfolder"

    def source(self):
        git = tools.Git(verify_ssl=False)
        git.clone(**self.conan_data["sources"][self.version])

    def build(self):
        print("============= libyaml build begin =============")
        autotools_dynamic = AutoToolsBuildEnvironment(self)
        sysroot = os.environ.get("CONAN_CMAKE_SYSROOT", default="")
        chost = os.environ.get("CHOST")
        self.run("./bootstrap --chost={}".format(chost))

        args = []
        if self.options.shared:
            args.append("--enable-shared")
        
        autotools_dynamic.flags.append(f"--sysroot={sysroot}")
        autotools_dynamic.configure(args=args)
        autotools_dynamic.make()
        print("============= libyaml build end =============")

    def package(self):
        self.copy("permissions.ini", src="", dst="")
        self.copy("libyaml.so", src="src/.libs", dst="usr/lib64", symlinks=True)
        self.copy("libyaml-0.so.2", src="src/.libs", dst="usr/lib64", symlinks=True)
        self.copy("libyaml-0.so.2.0.9", src="src/.libs", dst="usr/lib64", symlinks=True)
        self.copy("yaml.h", src="include", dst="include")

    def package_info(self):
        self.cpp_info.libdirs = ["usr/lib64"]
        self.cpp_info.libs = ["libyaml"]
        self.cpp_info.includedirs = ["include"]
